/*
 * Copyright 2016 jeasonlzy(廖子尧)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mingtu.dzpatrol.callback;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.Window;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.base.Request;
import com.mingtu.dzpatrol.activity.LoginActivity;
import com.mingtu.dzpatrol.base.BaseActivity;
import com.mingtu.dzpatrol.utils.ActivityUtil;
import com.mingtu.dzpatrol.utils.Constant;
import com.mingtu.dzpatrol.utils.IntentUtils;
import com.mingtu.dzpatrol.utils.SPTools;
import com.mingtu.dzpatrol.view.LoadingDialog;
import com.mingtu.dzpatrol.view.MyDialog;


import okhttp3.Response;

/**
 * ================================================
 * 版    本：1.0
 * 修订历史：
 * ================================================
 */
public abstract class StringDialogCallback extends StringCallback {

    private LoadingDialog dialog;
    private String baseUrl;
    private String token;
    private Activity activity;
    private static Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 401:
                    BaseActivity baseActivity = (BaseActivity) ActivityUtil.getTopActivity();
                    MyDialog myDialog = null;
                    try {
                        myDialog = baseActivity.getLogoutDialog();
                        if (myDialog == null) { //防止重复的创建dialog
                            baseActivity.showLogoutDialog(handler);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
                default:
                    break;
            }
        }
    };

    public StringDialogCallback(Activity activity) {
        this.activity = activity;
        try {
            activity.runOnUiThread(new Runnable() {
                public void run() {
                    dialog = new LoadingDialog(activity);
                    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    dialog.setCanceledOnTouchOutside(false);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStart(Request<String, ? extends Request> request) {
        token = SPStaticUtils.getString(SPTools.token);
        baseUrl = request.getBaseUrl();
        if (!StringUtils.isEmpty(token)) {
            if (!baseUrl.equals(Constant.POST_LOGIN)) {
                request.headers("token", token);
            }
        }

        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public void onFinish() {
        if (dialog != null && dialog.isShowing()) {
            try {
                dialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String convertResponse(Response response) throws Throwable {

        String result = super.convertResponse(response);
        JSONObject jsonObject = JSON.parseObject(result);
        if (baseUrl.equals(Constant.GET_AREA)) {
            return result;
        } else {
            int code = Integer.parseInt(jsonObject.getString("code"));
            String msg = jsonObject.getString("msg");
            if (code == 0) {
                if (!StringUtils.isEmpty(result)) {
                    return result;
                } else {
                    ToastUtils.showLong(msg);
                    return null;
                }
            } else if (code == 401) {//token过期,重新登录
                //token 为空的时候，也会出现401的情况，这个时候不应该弹出异地登录的dialog
                if (StringUtils.isEmpty(token)) {
                    if (!(activity instanceof LoginActivity)) { //为了防止在登录界面的时候再次创建登录界面
                        if (!SPStaticUtils.contains(SPTools.token)) {
                            ToastUtils.showLong("请先进行登录操作！");
                        }
                        //防止两次跳转
                        if (!baseUrl.equals(Constant.POST_UPLOAD_LOCATION)) {
                            IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), LoginActivity.class);
                            ActivityUtil.removeAllActivity();
                        }
                    }
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Message msg = Message.obtain();
                            msg.what = 401;
                            handler.sendMessage(msg);
                        }
                    }).start();
                }

                return null;
            } else if (code == 500) {
                ToastUtils.showLong(msg);
                return null;
            } else {
                ToastUtils.showLong(result);
                return null;
            }

        }

    }


}
